<template>
	<div class="app-editor-container">
		<van-field
			v-bind="$attrs"
			:type="type"
			:class="[
				`app-mob-input__${type}`,
				`app-mob-input-${name}`,
			]"
			v-model="curValue"
			:disabled="disabled"
			:readonly="readOnly"
			:placeholder="placeholder"
			@focus="handleFocus"
			@blur="handleBlur"
			@click="handleClick"
			@input="handleChange"
		>
		</van-field>
		<div v-if="unit " class="unit-text">{{ unit }}</div>
	</div>
</template>
<script setup lang="ts">
import { debounce, IEvent } from '@/core';
import { inputProps } from './input';

interface EditorEmit {
	(name: 'editor-event', value: IEvent<string>): void;
}
const props = defineProps(inputProps);
const emit = defineEmits<EditorEmit>();
const curValue = ref('');

watch(
	() => props.value,
	(newVal: any, oldVal: any) => {
		curValue.value = newVal;
	},
	{
		immediate: true,
	}
);

const handleChange = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	let { value } = target;
	const params = {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	};
	isDebounce(params);
};
const handleFocus = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	let { value } = target;
	emitFun({
		name: `${props.name}`,
		action: 'editorFocus',
		data: value,
	});
};
const handleBlur = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	let { value } = target;
	emitFun({
		name: `${props.name}`,
		action: 'editorBlur',
		data: value,
	});
};
const handleClick = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	let { value } = target;
	emitFun({
		name: `${props.name}`,
		action: 'editorClick',
		data: value,
	});
};

const emitFun = (params: any) => {
	emit('editor-event', params);
};

const isDebounce = (params: IEvent<string>) => {
	debounce(emitFun, [params], getCurrentInstance(), 300);
};
</script>
